package com.web.base.user.dao;

import com.blue.jdbc.BaseDao;
import com.web.base.user.model.User;
import com.web.base.user.model.UserWechat;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;

/**
 * 员工-微信号数据库访问
 * 
 * @author 代码由 blue-code 框架生成
 * @since 1.0 2017年05月19日
 */
@Repository
public class UserWechatDao extends BaseDao<UserWechat>
{

	public UserWechatDao()
	{
	}
	
	@Override
	protected void query(StringBuilder sql, UserWechat param)
	{
		if (param != null)
		{
			if (param.getWechatId() != null && param.getWechatId() > 0)
				sql.append(" and a.wechat_id=:wechatId");
				
			if (param.getUserId() != null && param.getUserId() > 0)
				sql.append(" and a.user_id=:userId");
				
			if (param.getCode() != null && !param.getCode().isEmpty())
				sql.append(" and a.code=:code");
				
		}
		sql.append(" order by a.id desc");
	}
	
	public void update(Integer wechatId, Integer userId, String wxOpenId, String wechatCode)
	{
		UserWechat userWechat = this.getObject("wechatId", wechatId, "userId", userId);
		if (userWechat == null)
			userWechat = this.getObject("code", wechatCode, "userId", userId);

		if (userWechat == null)
		{
			userWechat = new UserWechat();
			userWechat.setWechatId(wechatId);
			userWechat.setUserId(userId);
			userWechat.setCode(wechatCode);
			userWechat.setWxOpenId(wxOpenId);
			this.save(userWechat);
		}
		else
		{
			userWechat.setWxOpenId(wxOpenId);
			userWechat.setCode(wechatCode);
			this.update(userWechat);
		}
	}
	
	public User loginByOpenId(Integer wechatId, String openId)
	{
		Map<String, Object> param = new HashMap<>();
		param.put("wechatId", wechatId);
		param.put("openId", openId);
		String sql = "select a.* from uc_user a, uc_user_wechat uw"
				+ " where a.id=uw.employee_id and uw.wechat_id=:wechatId and uw.wx_open_id=:openId";
		return jdbcObjectTemplate.get(User.class, sql, param);
	}
	
}
